package org.rcgwt.client.ui.grid.renderer;

import org.rcgwt.client.ui.grid.internal.model.ICellModel;
import org.rcgwt.client.ui.grid.model.IEditableDataModel;

import com.google.gwt.dom.client.Element;
import com.google.gwt.dom.client.Node;
import com.google.gwt.event.dom.client.KeyCodes;
import com.google.gwt.event.dom.client.KeyDownEvent;
import com.google.gwt.event.dom.client.KeyDownHandler;
import com.google.gwt.user.client.ui.HasText;
import com.google.gwt.user.client.ui.TextBox;
import com.google.gwt.user.client.ui.Widget;

public class DefaultEditCellRenderer extends AbstractCellRenderer implements
        ICellEditorRenderer {

    @Override
    public Element renderEdit(final IViewRenderContext viewRenderContext,
            Element element, final ICellModel cell) {
        // Supprime les sous éléments éventuelles
        while (element.getChildNodes().getLength() > 0) {
            Node child = element.getChildNodes().getItem(0);
            element.removeChild(child);
        }

        final TextBox editBox = new TextBox();
        editBox.addKeyDownHandler(new KeyDownHandler() {

            @Override
            public void onKeyDown(KeyDownEvent event) {
                if (event.getNativeKeyCode() == KeyCodes.KEY_ENTER) {
                    save(viewRenderContext, cell, editBox);
                }

            }
        });
        editBox.setText(String.valueOf(getValue(viewRenderContext
                .getGridRenderContext(), cell)));
        element.appendChild(editBox.getElement());

        viewRenderContext.getGridRenderContext().getGridModel().getGridWidget()
                .getWidgetsRegistry().add(editBox);

        return null;
    }

    @Override
    protected Object getValue(IGridRenderContext renderContext, ICellModel cell) {
        return renderContext.getGridModel().getGridWidget().getDataModel()
                .getValueAt(cell.getModelIndex(),
                        cell.getColumnModel().getColumn().getName());
    }

    private void save(IViewRenderContext viewRenderContext,
            ICellModel cellModel, HasText hasText) {

        ((IEditableDataModel) viewRenderContext.getGridRenderContext()
                .getGridModel().getGridWidget().getDataModel()).setValueAt(
                hasText.getText(), cellModel.getModelIndex(), cellModel
                        .getColumnModel().getColumn().getName());
        // update(renderContext, element, cell, childUpdate);
    }

    @Override
    protected Widget getWidget(IGridRenderContext renderContext, ICellModel cell) {
        // TODO Auto-generated method stub
        return null;
    }

}
